import { useState } from "react";
import "./index.css";
import Stats from "./stats";
import Todos from "./todos";

const App = () => {
    let [data, setData] = useState([
        {
            id: 1,
            title: "本赛季要上王者",
            done: true
        }, {
            id: 2,
            title: "从老婆手里要到卖皮肤的钱",
            done: false
        }
    ])
    const addTodo = (title) => {
        setData([...data, {
            id: Date.now(),
            title,
            done: false
        }])
    }
    const removeTodo = (id) => {
        setData(data.filter(item => item.id !== id))
    }
    const changeDone = (id, done) => {
        setData(data.map(item => {
            if (item.id === id) {
                return {
                    ...item,
                    done
                }
            }
            return item
        }))
    }
    const editDone = (id, title) => {
        setData(data.map(item => {
            if (item.id === id) {
                return {
                    ...item,
                    title
                }
            }
            return item
        }))
    }
    const keyDownEventer = (e) => {
        if (e.keyCode === 13) { //回车键
            let val = e.target.value;
            if (val.trim()) {
                addTodo(val);
                e.target.value = "";
            }
        }
    }
    return (
        <div id="todoapp">
            <h1>todo</h1>
            <div className="content">
                <div id="create-todo">
                    <input id="new-todo" placeholder="What needs to be done?" autoComplete="off" type="text" onKeyDown={keyDownEventer} />
                </div>
                <Todos data={data} changeDone={changeDone} removeTodo={removeTodo} editDone={editDone} />
                <Stats data={data} />
            </div>
        </div>
    )
}
export default App;